package cn.org.eshow.service.impl;

import cn.org.eshow.bean.query.FavoriteQuery;
import cn.org.eshow.common.page.Page;
import cn.org.eshow.dao.FavoriteDao;
import cn.org.eshow.model.Favorite;
import cn.org.eshow.model.User;
import cn.org.eshow.service.FavoriteManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.WebService;
import java.util.List;

@WebService(serviceName = "FavoriteService", endpointInterface = "cn.org.eshow.service.FavoriteManager")
@Service
public class FavoriteManagerImpl extends GenericManagerImpl<Favorite, Integer> implements FavoriteManager {

    @Autowired
    FavoriteDao favoriteDao;

    public FavoriteManagerImpl() {
    }

    @Autowired
    public FavoriteManagerImpl(FavoriteDao favoriteDao) {
        super(favoriteDao);
        this.favoriteDao = favoriteDao;

    }

    @Override
    public List<Favorite> list(FavoriteQuery query) {
        return favoriteDao.list(query);
    }

    @Override
    public Page<Favorite> search(FavoriteQuery query) {
        return favoriteDao.search(query);
    }

    @Override
    public Favorite check(FavoriteQuery query) {
        List<Favorite> list = favoriteDao.list(query);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public Favorite save(Favorite favorite, User user) {
        FavoriteQuery query = new FavoriteQuery();
        query.setUserId(user.getId());
        query.setProductId(favorite.getProduct() == null ? null : favorite.getProduct().getId());
        Favorite old = check(query);
        if (old == null) {
            favorite.setUser(user);
            return favoriteDao.save(favorite);
        }
        old.setEnabled(Boolean.TRUE);
        return favoriteDao.save(old);
    }

    @Override
    public Favorite updateEnabled(Favorite favorite, User user) {
        FavoriteQuery query = new FavoriteQuery();
        query.setUserId(user.getId());
        query.setProductId(favorite.getProduct() == null ? null : favorite.getProduct().getId());
        Favorite old = check(query);
        old.setEnabled(!old.getEnabled());
        return favoriteDao.save(old);
    }

}